<template>
  <el-dialog
    :title="title"
    v-model="props.params.visible"
    width="1100px"
    append-to-body
    :before-close="cancel"
  >
    <el-form
      :model="addForm"
      ref="addRef"
      :inline="true"
      :rules="addRules"
      label-width="80px"
    >
      <el-form-item label="销售方" prop="salesPersonId">
        <el-select
          v-model="addForm.salesPersonId"
          filterable
          remote
          reserve-keyword
          placeholder="请选择销售方"
          :remote-method="getUserOption"
          :loading="userLoading"
          clearable
          style="width: 220px"
          @change="handleChooseUser"
        >
          <el-option
            v-for="item in userOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="成交价" prop="salesPrice">
        <el-input
          v-model="addForm.salesPrice"
          placeholder="请输入"
          clearable
          style="width: 220px"
        />
      </el-form-item>
      <el-form-item label="成交时间" prop="salesTime">
        <el-date-picker
          style="width: 220px"
          v-model="addForm.salesTime"
          type="datetime"
          placeholder="打款时间"
          value-format="YYYY-MM-DD HH:mm:ss"
          :shortcuts="shortcuts"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="到款状态" prop="paymentStatus">
        <el-select
          v-model="addForm.paymentStatus"
          filterable
          clearable
          @change="paymentStatusChange"
          placeholder="请选择"
          style="width: 220px"
        >
          <el-option
            v-for="item in payment_status"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="到款时间" prop="paymentTime">
        <el-date-picker
          style="width: 220px"
          v-model="addForm.paymentTime"
          type="datetime"
          placeholder="打款时间"
          value-format="YYYY-MM-DD HH:mm:ss"
          :shortcuts="shortcuts"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="到款方式" prop="paymentWay">
        <el-select
          v-model="addForm.paymentWay"
          filterable
          clearable
          remote
          :remote-method="getPayment_way"
          allow-create
          placeholder="请选择"
          style="width: 220px"
          @change="paymentChange"
        >
          <el-option
            v-for="item in payment_way"
            :key="item.id"
            :label="item.paymentWay"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="销售客户" prop="customerName">
        <el-input
          v-model="addForm.customerName"
          placeholder="请输入"
          clearable
          style="width: 220px"
        />
      </el-form-item>
      <el-form-item label="销售提成" prop="salesCommissions">
        <el-input
          v-model="addForm.salesCommissions"
          placeholder="请输入"
          clearable
          style="width: 220px"
        />
      </el-form-item>
      <el-form-item label="备注" prop="remark">
        <el-select
          v-model="addForm.remark"
          filterable
          clearable
          remote
          allow-create
          :remote-method="getSalesRemark"
          placeholder="请选择"
          style="width: 220px"
          @change="salesRemarkChange"
        >
          <el-option
            v-for="item in salesRemarkOptions"
            :key="item.id"
            :label="item.salesRemark"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="其它" prop="otherRemark">
        <el-select
          v-model="addForm.otherRemark"
          filterable
          clearable
          remote
          allow-create
          :remote-method="getOtherRemark"
          placeholder="请选择"
          style="width: 220px"
          @change="otherRemarkChange"
        >
          <el-option
            v-for="item in otherRemarkOptions"
            :key="item.id"
            :label="item.otherRemark"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="商品编码" prop="ref">
        <el-input
          :disabled="basicInfo"
          v-model="addForm.ref"
          placeholder="请输入"
          clearable
          style="width: 220px"
        />
      </el-form-item>
      <el-form-item label="商品型号" prop="model">
        <el-input
          :disabled="basicInfo"
          v-model="addForm.model"
          placeholder="请输入"
          clearable
          style="width: 220px"
        />
      </el-form-item>
      <el-form-item label="品牌" prop="brand">
        <el-select
          v-model="addForm.brand"
          filterable
          reserve-keyword
          clearable
          :disabled="basicInfo"
          remote
          :remote-method="getItemBrand"
          default-first-option
          placeholder="请选择品牌"
          style="width: 220px"
        >
          <el-option
            v-for="item in item_brand"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="回收价格" prop="recyclePrice">
        <el-input-number
          :disabled="basicInfo"
          v-model="addForm.recyclePrice"
          placeholder="请输入"
          clearable
          style="width: 220px"
        />
      </el-form-item>
      <el-form-item label="回收编码" prop="recycleCode">
        <el-input
          :disabled="basicInfo"
          v-model="addForm.recycleCode"
          placeholder="请输入"
          clearable
          style="width: 220px"
        />
      </el-form-item>
      <el-form-item label="回收备注" prop="recycleRemark">
        <el-input
          :disabled="basicInfo"
          v-model="addForm.recycleRemark"
          placeholder="请输入"
          clearable
          style="width: 220px"
        />
      </el-form-item>
      <!-- <el-form-item label="商品正面" prop="file1">
        <el-upload
          v-model:file-list="fileList"
          ref="upload"
          list-type="picture-card"
          :on-preview="handlePictureCardPreview"
          :limit="1"
          :disabled="true"
          :on-exceed="handleExceed"
          accept=".jpg,.png,.jpeg"
          :auto-upload="false"
        >
          <el-icon><Plus /></el-icon>
        </el-upload>
      </el-form-item>
      <el-form-item label="商品背面" prop="file2">
        <el-upload
          v-model:file-list="fileListBack"
          ref="upload"
          list-type="picture-card"
          :on-preview="handlePictureCardPreview"
          :limit="1"
          :disabled="true"
          :on-exceed="handleExceed"
          accept=".jpg,.png,.jpeg"
          :auto-upload="false"
        >
          <el-icon><Plus /></el-icon>
        </el-upload>
      </el-form-item> -->
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </template>
  </el-dialog>
</template>
<script setup>
import {
  addRegister,
  getRegister,
  updateRegister,
  getPaymentWay,
  salesRemark,
  otherRemark,
} from "@/api/sales/register";
import { optionSelect } from "@/api/system/skesItem";
import { userOptionSelect } from "@/api/system/user";
import useUserStore from "@/store/modules/user";
import { listData } from "@/api/system/dict/data";

import { computed, watchEffect } from "vue";
const props = defineProps({
  params: Object,
  visible: Boolean,
  options: Array,
});
const emits = defineEmits(["update:visible", "refresh"]);
const { proxy } = getCurrentInstance();
const userStore = useUserStore();
const { payment_status, goods_category, goods_status } = proxy.useDict(
  "payment_status",
  "goods_category",
  "goods_status"
);
const title = computed(() =>
  props.params.type === "add" ? "新增下架登记" : "修改下架登记"
);
const fileList = ref([]);
const fileListBack = ref([]);
const addForm = ref({
  salesPrice: undefined,
  salesTime: undefined,
  salesCommissions: undefined,
  paymentStatus: undefined,
  paymentStatusName: undefined,
  paymentTime: undefined,
  paymentWay: undefined,
  customerName: undefined,
  remark: undefined,
  otherRemark: undefined,
  ref: undefined,
  model: undefined,
  brand: undefined,
  recyclePrice: undefined,
  recycleCode: undefined,
});
const addRules = {
  itemId: [{ required: true, message: "商品不能为空", trigger: "blur" }],
  salesTime: [{ required: true, message: "成交时间不能为空", trigger: "blur" }],
  salesPrice: [{ required: true, message: "成交价不能为空", trigger: "blur" }],
  paymentStatus: [
    { required: true, message: "到款情况不能为空", trigger: "blur" },
  ],
  salesPersonId: [
    { required: true, message: "销售方不能为空", trigger: "blur" },
  ],
};
const shortcuts = [
  {
    text: "今天",
    value: new Date(),
  },
  {
    text: "昨天",
    value: () => {
      const date = new Date();
      date.setTime(date.getTime() - 3600 * 1000 * 24);
      return date;
    },
  },
  {
    text: "一周前",
    value: () => {
      const date = new Date();
      date.setTime(date.getTime() - 3600 * 1000 * 24 * 7);
      return date;
    },
  },
];
const basicInfo = ref(true);
const isUpdate = ref(false);
watchEffect(() => {
  const { visible, type } = props.params;
  if (visible) getDetail();
  isUpdate.value = type === "add" ? true : false;
});

const payment_way = ref([]);
async function getPayment_way(queryKey) {
  const { data } = await getPaymentWay({ queryKey });
  payment_way.value = data;
}
function paymentChange(val) {
  // 如果有id就传id和备注内容
  if(typeof val === 'number') {
    addForm.value.paymentWayId = val
    addForm.value.paymentWay = payment_way.value.find(i => i.id === val).paymentWay
  } else {
    addForm.value.paymentWayId = undefined
  }
}
getPayment_way(" ");
/** 品牌 */
const brandLoading = ref(false);
const item_brand = ref([]);
async function getItemBrand(query) {
  if (query) {
    brandLoading.value = true;
    let label = "";
    let val = "";
    if (isNaN(query)) {
      label = query;
    } else {
      val = query;
    }
    const { rows } = await listData({
      pageNum: 1,
      pageSize: 10,
      dictType: "item_brand",
      dictValue: val,
      dictLabel: label,
    });
    item_brand.value = rows.map((i) => {
      const { dictValue, dictLabel } = i;
      return {
        value: dictValue,
        label: dictLabel,
      };
    });
    brandLoading.value = false;
  }
}

function paymentStatusChange(val) {
  try {
    const option = payment_status.value.find((i) => i.value === val);
    addForm.value.paymentStatusName = option.label;
  } catch (err) {}
}
/** 商品下拉框 */
const remoteLoading = ref(false);
const itemOptions = ref([]);
async function getItemOption(query) {
  if (query) {
    remoteLoading.value = true;
    const { data } = await optionSelect({ queryKey: query });
    itemOptions.value = data.map((i) => {
      const { id, brand, ref: re, recyclePrice, model, expressNo } = i;
      return {
        value: i.id,
        label: `${id},${brand},${re},${recyclePrice},${model},${
          expressNo || ""
        }`,
        recyclePrice: i.recyclePrice,
      };
    });
    remoteLoading.value = false;
  }
}
// 其他
const otherRemarkOptions = ref([]);
async function getOtherRemark(query) {
  const { data } = await otherRemark({ queryKey: query });
  otherRemarkOptions.value = data;
}
function otherRemarkChange(val) {
  // 如果有id就传id和备注内容
  if (typeof val === "number") {
    addForm.value.otherRemarkId = val;
    addForm.value.otherRemark = otherRemarkOptions.value.find(
      (i) => i.id === val
    ).otherRemark;
  } else {
    addForm.value.otherRemarkId = undefined;
  }
}
getOtherRemark(" ");

// 备注
const salesRemarkOptions = ref([]);
async function getSalesRemark(query) {
  if (query) {
    const { data } = await salesRemark({ queryKey: query });
    salesRemarkOptions.value = data;
  }
}
function salesRemarkChange(val) {
  // 如果有id就传id和备注内容
  if (typeof val === "number") {
    addForm.value.remarkId = val;
    addForm.value.remark = salesRemarkOptions.value.find(
      (i) => i.id === val
    ).salesRemark;
  } else {
    addForm.value.remarkId = undefined;
  }
}
getSalesRemark(" ");
/** 用户下拉框 */
const userLoading = ref(false);
const userOptions = ref([]);
async function getUserOption(query) {
  if (query) {
    userLoading.value = true;
    const { data } = await userOptionSelect({ queryKey: query });
    userOptions.value = data.map((i) => {
      const { userId, nickName, userName } = i;
      return {
        value: i.userId,
        label: `${userId},${nickName},${userName}`,
        nickName,
        userName,
      };
    });
    userLoading.value = false;
  }
}
function handleChooseUser(userId) {
  const { nickName, userName } = userOptions.value.find(
    (i) => i.value === userId
  ) || {
    nickName: undefined,
    userName: undefined,
  };
  addForm.value.salesPerson = nickName;
  addForm.value.salesPersonName = userName;
}
getItemOption(" ");
getUserOption(" ");
/** 获取商品详情 */
function getDetail() {
  getRegister(props.params.id).then((response) => {
    const {
      salesPersonId,
      paymentStatus,
      watchImageUrl,
      watchImageUrlBack,
      brand,
    } = response.data;
    const sId =
      typeof salesPersonId === "number" ? salesPersonId + "" : salesPersonId;
    const pS =
      typeof paymentStatus === "number" ? paymentStatus + "" : paymentStatus;
    addForm.value = {
      ...response.data,
      paymentStatus: pS,
    };
    getItemBrand(brand);
    fileList.value[0] = { url: watchImageUrl };
    fileListBack.value[0] = { url: watchImageUrlBack };
    if (props.params.type === "edit") {
      addForm.value.salesPersonId = sId;
    } else {
      addForm.value.salesPersonId = userStore.id;
      addForm.value.salesPerson = userStore.nickName;
      addForm.value.salesPersonName = userStore.name;
    }
  });
}
/** 重置表单  */
function reset() {
  addForm.value.salesPerson = undefined;
  proxy.resetForm("addRef");
}
/** 提交按钮 */
function submitForm() {
  proxy.$refs["addRef"].validate((valid) => {
    if (valid) {
      if (props.params.type === "add") {
        addRegister(addForm.value).then((response) => {
          proxy.$modal.msgSuccess("新增回收登记成功");
          emits("refresh");
          cancel();
        });
      } else {
        updateRegister(addForm.value).then((response) => {
          proxy.$modal.msgSuccess("修改回收登记成功");
          emits("refresh");
          cancel();
        });
      }
    }
  });
}
/** 取消按钮 */
function cancel() {
  reset();
  emits("update:visible", false);
}
</script>
